//
//  SeekoBoardListTableViewController.m
//  Moko
//
//  Created by cj848 on 11. 7. 25..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//


#import "MokoAppDelegate.h"
#import "BoardListAllVO.h"
#import "SeekoArticleTableViewController.h"
#import "SeekoBoardListTableViewController.h"
#import "MemoWriteViewController.h"
#import "ParsingDirector.h"
#import "UIImageCategory.h"
@implementation SeekoBoardListTableViewController
@synthesize listLink, listTitle;
@synthesize boardList, searchVO;
@synthesize reloading=_reloading;
-(void)deviceShaken {
    GET_APPDELEGATE;
    NSString* param = [NSString stringWithFormat:@"%@/zboard4/zboard.php?%@", delegate.configVO.siteHostAddress,[searchVO getParam]];
    [delegate.httpClient requestURL:[NSString stringWithFormat:@"%@/zboard4/zboard.php?%@", delegate.configVO.siteHostAddress, param] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( alertView.tag == 100 && buttonIndex == 1) {
        GET_APPDELEGATE;
        [self presentModalViewController:delegate.loginViewController animated:YES];
    }
}
-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil title:(NSString*)title link:(NSString*)link {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if( self ) {
        
        self.listTitle = title;
        self.listLink = link;
        //boardList = [[NSMutableArray alloc] init];
        searchVO = [[BoardSearchVO alloc] init];
        int idx = [listLink indexOf:@"="];
        NSString* idstr = [listLink substringFromIndex:idx+1];
        [searchVO.dic setObject:idstr forKey:@"id"];
        // 백버튼 커스터마이징
        // backBarButtonItem 이었나 암튼 이거로는 커스텀뷰가 안돼서 이렇게 지정
        UIImage* image = [UIImage imageNamed:@"back_left_button.png"];
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:image forState:UIControlStateNormal];
        [button addTarget:self.navigationController action:@selector(backStep) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, 0, image.size.width/2, image.size.height/2);
        UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.leftBarButtonItem = item;
        [item release];
    }
    return self;
}
-(void)loadFirstPage {
    GET_APPDELEGATE;
    [searchVO.dic setObject:[NSString stringWithFormat:@"%d", 1] forKey:@"page"];
    [searchVO.dic setObject:@"" forKey:@"keyword"];
    NSString* param = [searchVO getParam];
    [delegate.httpClient requestURL:[NSString stringWithFormat:@"%@/zboard4/zboard.php?%@", delegate.configVO.siteHostAddress,param] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}
-(void)writeButton {
    
    GET_APPDELEGATE;
    NSDictionary* dic = [[NSDictionary alloc] initWithObjectsAndKeys:[searchVO.dic objectForKey:@"id"], @"id",self.title, @"title", nil];
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
        delegate.writeViewController = [[WriteViewController alloc] initWithNibName:@"WriteAndModifyViewController" bundle:[NSBundle mainBundle] isModify:NO vo:dic];
    else
        delegate.writeViewController = [[WriteViewController alloc] initWithNibName:@"WriteAndModifyViewController-iPad" bundle:[NSBundle mainBundle] isModify:NO vo:dic];
    
    [dic release];
    [self.navigationController pushViewController:delegate.writeViewController animated:YES];
}
- (void)dealloc
{
    [listLink release];
    [listTitle release];
    [boardList release];
    [searchVO release];
    [searchBarController release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = listTitle;
    self.tableView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
    searchBarController.searchBar.tintColor = RGB(40, 130, 181);
    GET_APPDELEGATE;
    [delegate.httpClient requestURL:self.listLink httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
    
    if (self.rHeaderView == nil) {
		self.rHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, [[UIScreen mainScreen] bounds].size.width, self.tableView.bounds.size.height)];
		self.rHeaderView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
		[self.tableView addSubview:self.rHeaderView];
		self.tableView.showsVerticalScrollIndicator = YES;
		[self.rHeaderView release];
	}
    if (self.rFooterView == nil) {
        float y = [self.tableView frame].size.height;
        if( y < [self tableViewHeight] )
            y = [self tableViewHeight];
        self.rHeaderView = [[EGORefreshTableFooterView alloc] initWithFrame:CGRectMake(0.0f, y, [[UIScreen mainScreen] bounds].size.width, self.tableView.bounds.size.height + 120.0f)];
		self.rFooterView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
		[self.tableView addSubview:self.rFooterView];
		self.tableView.showsVerticalScrollIndicator = YES;
		[self.rFooterView release];
    }
    // scope bar 사용 기본은 보여주지 않음
    searchBarController.searchBar.showsScopeBar = NO;
    [searchBarController.searchBar sizeToFit];
    self.tableView.tableHeaderView = searchBarController.searchBar;
    searchBarController.searchBar.selectedScopeButtonIndex = 0;
    // 첫번째 체인으로 흔들기 동작 인식용
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deviceShaken) name:@"DeviceShaken" object:nil];
    [self repositionRefreshFooterView];
}
-(void)loginAction {
    GET_APPDELEGATE;
    [self presentModalViewController:delegate.loginViewController animated:YES];
}
- (void)viewDidUnload
{
    [searchBarController release];
    searchBarController = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [boardList count];
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString* title = [NSString stringWithFormat:@"%@ 페이지", [searchVO.dic objectForKey:@"page"]];
    NSString* keyword = [searchVO.dic objectForKey:@"keyword"];
    if( [keyword length] != 0 )
        title = [NSString stringWithFormat:@"%@, 검색어 : %@", title, keyword];
    return title;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.backgroundColor = [UIColor clearColor];
        UIImage* leftImage = [UIImage imageNamed: @"listarrow.png"];
        leftImage = [leftImage ResizedImage:CGRectMake(0, 0, leftImage.size.width * 0.75, leftImage.size.height * 0.75)];
        cell.imageView.image = leftImage;
        cell.textLabel.opaque = NO;
        cell.textLabel.highlightedTextColor = [UIColor whiteColor];
        UILabel* detailTextLabel = nil;
        if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
            detailTextLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width * 0.2, cell.frame.size.height-1)] autorelease];
        else
            detailTextLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width * 0.1, cell.frame.size.height-1)] autorelease];
        detailTextLabel.textColor = RGB(86, 86, 86);
        detailTextLabel.backgroundColor = [UIColor clearColor];
        detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:12.0f];
        detailTextLabel.numberOfLines = 0;
        cell.accessoryView = detailTextLabel;
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0f];
        
        UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [cell addGestureRecognizer:longPressGr];
        [longPressGr release];
    }
    cell.tag = indexPath.row;
    if( [boardList count]-1 >= indexPath.row ) {
        BoardListVO* vo = (BoardListVO*)[boardList objectAtIndex:indexPath.row];
        cell.textLabel.text = ((BoardListVO*)[boardList objectAtIndex:indexPath.row]).title;
        int count = [vo.commentCount intValue];
        // 짝수 홀수에 따른 백그라운드 색 변경
        if( (indexPath.row & 1) == 0 ) {
            cell.textLabel.textColor = [UIColor blackColor];
            cell.contentView.backgroundColor = RGB(247, 247, 247);
            cell.accessoryView.backgroundColor = cell.contentView.backgroundColor;
            CGRect frame = cell.frame;
            frame.size.height += cell.textLabel.frame.size.height + ((UILabel*)cell.accessoryView).frame.size.height + 5;
            cell.frame = frame;
        }
        else {
            cell.textLabel.textColor = [UIColor blackColor];
            cell.contentView.backgroundColor = RGB(237, 237, 237);
            cell.accessoryView.backgroundColor = cell.contentView.backgroundColor;
            CGRect frame = cell.frame;
            frame.size.height += cell.textLabel.frame.size.height + ((UILabel*)cell.accessoryView).frame.size.height + 5;
            cell.frame = frame;
        }
        if( vo.nameText != nil && [vo.nameText isEqualToString:@"Master"] )
            cell.textLabel.textColor = RGB(40, 130, 181);
        else if( count > 20 )
            cell.textLabel.textColor = [UIColor redColor];
        if( vo.nameText != nil ) {
            ((UILabel*)cell.accessoryView).text = [NSString stringWithFormat:@"%@\r\n댓글 %@", vo.nameText, vo.commentCount];
        }
    }
    else {
        cell.textLabel.text = @"";
        ((UILabel*)cell.accessoryView).text = @"";
    }
    
    // Configure the cell...
    
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */
- (void)finishLoading:(NSData*)data {
    [self.tableView setContentOffset:CGPointMake(0, 0)];
    GET_APPDELEGATE;
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    BoardListAllVO* allVO = [director getArticleList];
    if( allVO != nil ) {
        self.boardList = allVO.boardListVOArr;
        if( allVO.page != 0 )
            [searchVO.dic setValue:[NSString stringWithFormat:@"%d", allVO.page] forKey:@"page"];
        
        if( [delegate.httpClient didLogin] == YES && allVO.writable == YES ) {
            UIImage* image = [UIImage imageNamed:@"write_right_button.png"];
            UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:image forState:UIControlStateNormal];
            if( [self.navigationController.navigationBar bounds].size.height > image.size.height )
                button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
            else
                button.frame = CGRectMake(0, 0, 25, 25);
            [button addTarget:self action:@selector(writeButton) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:button];
            [self.navigationItem setRightBarButtonItem:item];
            [item release];
        } else {
            self.navigationItem.rightBarButtonItem = nil;
        }
        [self.tableView reloadData];
        [self dataSourceDidFinishLoadingNewData];
        [self repositionRefreshFooterView];
    }
}
-(void)longPress:(id)sender {
    
    UILongPressGestureRecognizer* gr = (UILongPressGestureRecognizer*)sender;
    if ([gr state] == UIGestureRecognizerStateBegan) {
        UIView* view = [gr view];
        selectedIndex = view.tag;
        UIActionSheet* sheet = [[UIActionSheet alloc] init];
        sheet.title = [NSString stringWithFormat:@"선택된 회원 : %@ 님", ((BoardListVO*)[boardList objectAtIndex:selectedIndex]).nameText];
        sheet.delegate = self;
        if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
            sheet.cancelButtonIndex = 0;
            [sheet addButtonWithTitle:@"취소"];
        }
        
        [sheet addButtonWithTitle:@"회원 정보"];
        GET_APPDELEGATE;
        if( delegate.httpClient.isLogin == YES ) 
            [sheet addButtonWithTitle:@"쪽지 보내기"];
        [sheet addButtonWithTitle:@"이름으로 검색"];
        sheet.tag = 10;
        [sheet showFromTabBar:self.tabBarController.tabBar];
        [sheet release];
    }
}
-(void)memberInfo:(NSData*)data {
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    [director memberInfo];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 댓글 액션 시트
    if( actionSheet.tag == 10 ) {
        BoardListVO* vo = [boardList objectAtIndex:selectedIndex];
        
        // 회원 정보
        if(buttonIndex == actionSheet.cancelButtonIndex + 1) {
            NSString* addr = [NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/view_info2.php?member_no=%@", vo.userId];
            GET_APPDELEGATE;
            [delegate.httpClient requestURL:addr httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(memberInfo:)];
        }
        // 이름으로 검색
        else if( actionSheet.numberOfButtons-1 == buttonIndex ) {
            [searchBarController setActive:YES];
            [self searchDisplayController:nil shouldReloadTableForSearchScope:0];
            searchBarController.searchBar.text = [vo.nameText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            [self searchBarSearchButtonClicked:searchBarController.searchBar];
        }  
        // 쪽지 보내기
        else if( buttonIndex != 0 && buttonIndex != -1 ) {
            MemoWriteViewController* memoViewController;
            if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
                memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController" bundle:nil];
            else
                memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController-iPad" bundle:nil];
            memoViewController.toUserId = vo.userId;
            memoViewController.toUserName = vo.nameText;
            memoViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self presentModalViewController:memoViewController animated:YES];
            [memoViewController release];
        }
    }
}
#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BoardListVO* vo = (BoardListVO*)[boardList objectAtIndex:indexPath.row];
    if( ((BoardListVO*)[boardList objectAtIndex:indexPath.row]).link != nil ) {
        // 푸쉬한 뒤에 릴리즈 오토릴리즈 해버리면 좆망됨 CALayer release message sent to deallocated instance 에러 뜸... 푸쉬하고 팝하면 이미 릴리즈 된 상태
        SeekoArticleTableViewController* articleController = [[SeekoArticleTableViewController alloc] initWithNibName:@"SeekoArticleTableViewController" bundle:[NSBundle mainBundle] link:vo.link username:vo.nameText articleDate:vo.date isNoticeArticle:vo.isNoticeArticle];
        [self.navigationController pushViewController:articleController animated:YES];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"링크 없음" message:@"해당 글은 링크가 없어 들어갈 수 없습니다.\n로그인 하시겠습니까?." delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
        alert.tag = 100;
        [alert show];
        [alert release];
    }
}
// 검색바를 터치하면 검색 취소
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.placeholder = @"검색";
    [searchVO.dic setObject:@"" forKey:@"keyword"];
    [searchVO.dic setObject:@"1" forKey:@"page"];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    GET_APPDELEGATE;
    NSString* escapedStr = searchBar.text;
    [searchVO.dic setObject:escapedStr forKey:@"keyword"];
    [searchVO.dic setObject:@"1" forKey:@"page"];
    NSString* param = [searchVO getParam];
    param = [NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/zboard.php?%@", param];
    [delegate.httpClient requestURL:[NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/zboard.php?%@", param] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
    [searchBarController setActive:NO];
    NSString* selectedString = @"";
    switch( searchBar.selectedScopeButtonIndex ) {
        case 0:
            // 이름 검색
            selectedString=@"이름";
            break;
        case 1:
            // 제목 검색
            selectedString=@"제목";
            break;
        case 2:
            // 내용 검색
            selectedString=@"내용";
            break;
        case 3:
            // 제목+내용 검색
            selectedString=@"제목+내용";
            break;
    }
    searchBar.placeholder = [NSString stringWithFormat:@"[%@] : %@ 취소는 검색 바 터치~", selectedString, escapedStr];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    switch( searchOption ) {
        case 0:
            // 이름 검색
            [searchVO.dic setObject:@"on" forKey:@"sn"];
            [searchVO.dic setObject:@"off" forKey:@"ss"];
            [searchVO.dic setObject:@"off" forKey:@"sc"];
            break;
        case 1:
            // 제목 검색
            [searchVO.dic setObject:@"on" forKey:@"ss"];
            [searchVO.dic setObject:@"off" forKey:@"sn"];
            [searchVO.dic setObject:@"off" forKey:@"sc"];
            break;
        case 2:
            // 내용 검색
            [searchVO.dic setObject:@"on" forKey:@"sc"];
            [searchVO.dic setObject:@"off" forKey:@"ss"];
            [searchVO.dic setObject:@"off" forKey:@"sn"];
            break;
        case 3:
            // 제목+내용 검색
            [searchVO.dic setObject:@"on" forKey:@"ss"];
            [searchVO.dic setObject:@"on" forKey:@"sc"];
            [searchVO.dic setObject:@"off" forKey:@"sn"];
            break;
    }
    return YES;
}
#pragma mark - Refresh View Delegate

- (float)tableViewHeight {
    // calculate height of table view (modify for multiple sections)
    return self.tableView.rowHeight * [self tableView:self.tableView numberOfRowsInSection:0] + searchBarController.searchBar.frame.size.height + self.tableView.sectionHeaderHeight;
}
-(void)reloadHeader {
    GET_APPDELEGATE;
    int page = [[searchVO.dic objectForKey:@"page"] intValue];
    if( page != 1 )
        page--;
    [searchVO.dic setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
    NSString* param = [NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/zboard.php?%@",[searchVO getParam]];
    [delegate.httpClient requestURL:[NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/zboard.php?%@",param] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
    
}
-(void)reloadFooter {
    GET_APPDELEGATE;
    int page = [[searchVO.dic objectForKey:@"page"] intValue];
    page++;
    [searchVO.dic setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
    NSString* param = [NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/zboard.php?%@",[searchVO getParam]];
    
    [delegate.httpClient requestURL:[NSString stringWithFormat:@"http://www.cdpkorea.com/zboard4/zboard.php?%@",param] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
    
}
@end
